package com.songcha.module_bookdetail.ui.activity.detail

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.View.OnScrollChangeListener
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.bean.book.BookBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.handler.BookStatusHandler
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.util.*
import com.songcha.module_bookdetail.BuildConfig
import com.songcha.module_bookdetail.R
import com.songcha.module_bookdetail.bean.BookCommentListBean
import com.songcha.module_bookdetail.databinding.BookdetailActivityDetail2Binding
import com.songcha.module_bookdetail.ui.activity.catalog.BookCatalogActivity
import com.songcha.module_bookdetail.ui.activity.more_comment.MoreBookCommentActivity
import com.songcha.module_bookdetail.ui.adapter.BookCommentAdapter
import com.songcha.module_bookdetail.ui.dialog.BookReadTipDialog
import com.songcha.module_bookdetail.ui.view.BookDetailGestureFrameLayout
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

@Route(path="/bookdetail/BookDetailActivity")
class BookDetailActivity:BaseMvvmActivity<BookDetailViewModel,BookdetailActivityDetail2Binding>() ,View.OnClickListener,BookDetailGestureFrameLayout.IOnBookDetailFlipPageListener{
    private var mAdapter:BookCommentAdapter<BookdetailActivityDetail2Binding>?=null


    override fun getLayoutId(): Int {
        return R.layout.bookdetail_activity_detail2
    }

    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        intent?.let {
            viewModel.bookId=it.getStringExtra("book_id")?:""
        }

        if(viewModel.bookId.isEmpty()){
            ToastUtil.show("错误的书籍id")
            finish()
            return
        }

        UMengHelper.onUMEvent(this,"page_bookdetail_load")

        databinding.bookdetailRating.apply {
            setImageRes(R.mipmap.bookdetail_icon_star,R.mipmap.bookdetail_icon_unstar)
            setGapRatio(0.8f)
        }

        //ViewHelper.setVisibility(FunctionConfig.IS_BOOK_COMMENT_ENABLED,databinding.bookdetailRlComment,databinding.bookdetailRcvComment)
        //databinding.bookdetailClBottom.visibility=View.VISIBLE
        databinding.bookdetailLlParent.layoutParams=databinding.bookdetailLlParent.layoutParams.apply {
            this as MarginLayoutParams
            bottomMargin=66.dp2px()
        }

        viewModel.bookDetail.observe(this){data->
            initData()
            UMengHelper.onUMEvent(this,"page_bookdetail_load_success")
        }

        /*viewModel.bookCommentList.observe(this){data->
            initComment(data)
        }*/

       databinding.bookdetailLlToCatalog.setOnClickListener(this)
        databinding.bookdetailBtnBottomStartRead.setOnClickListener(this)
        databinding.bookdetailLlBottomAddtoShelf.setOnClickListener(this)
        //databinding.bookdetailFlParent.setOnBookDetailFlipPageListener(this)
        databinding.bookdetailLl.setOnClickListener(this)
        /* databinding.bookdetailTvMoreComment.setOnClickListener(this)
        databinding.bookdetailBtnStar.setOnClickListener(this)
        databinding.bookdetailBtnRead.setOnClickListener(this)
        databinding.bookdetailLl.setOnClickListener(this)
        databinding.bookdetailRcvComment.setOnClickListener(this)
        databinding.bookdetailNsv.setOnClickListener(this)
        databinding.bookdetailPlaceholder.setOnClickListener(this)
        databinding.bookdetailFlParent.setOnBookDetailFlipPageListener(this)

       */

        viewModel.isInBookShelf.observe(this){data->
            if(data){
                //databinding.bookdetailBtnStar.text="取消收藏"
                databinding.bookdetailTvBottomAddtoShelf.text="已加书架"
                //databinding.bookdetailTvBottomAddtoShelf.setTextColor(Color.parseColor("#999897"))
                databinding.bookdetailIvBottomAddtoShelf.setImageResource(R.mipmap.bookdetail_icon_bottom_inshelf)
            }else{
                //databinding.bookdetailBtnStar.text="收藏"
                databinding.bookdetailTvBottomAddtoShelf.text="加书架"
                //databinding.bookdetailTvBottomAddtoShelf.setTextColor(ColorUtil.getResourceColor(this,R.color.add_to_shelf_text))
                databinding.bookdetailIvBottomAddtoShelf.setImageResource(R.mipmap.bookdetail_icon_bottom_not_inshelf)
            }
        }


        if(Build.VERSION.SDK_INT>=23){
            databinding.bookdetailNsv.setOnScrollChangeListener(object :OnScrollChangeListener{
                override fun onScrollChange(
                    v: View?,
                    scrollX: Int,
                    scrollY: Int,
                    oldScrollX: Int,
                    oldScrollY: Int
                ) {
                    if(v==null) return
                    v as NestedScrollView
                    if(scrollY==v.getChildAt(0).measuredHeight-v.measuredHeight){
                        if(BuildConfig.DEBUG) return
                        toBookReader()
                    }
                }

            })
        }

    }

    override fun getLoadBackgroundColor(): Int {
        return Color.parseColor("#E7E1D1")
    }

    override fun onResume() {
        super.onResume()
        //onGetData()
        viewModel.isToBookReader=false
        viewModel.getIsBookInShelf()
    }


    override fun onGetData() {
        if(viewModel.bookId.isEmpty()) return
        viewModel.getBookdetail()
        viewModel.getIsBookInShelf()
        if(FunctionConfig.IS_BOOK_COMMENT_ENABLED){
            viewModel.getBookComment()
        }
    }

    override fun onRetry() {
        onGetData()
    }

    override fun isCalculateHearBarHeight(): Boolean {
        return false
    }

    override fun isNeedShowLoad(): Boolean {
        return true
    }

    private fun initData(){

        val bookDetail = viewModel.bookDetail.value?:return

        viewModel.saveBookBrowse()
        viewModel.saveBookDetail()

        databinding.bookdetailTvBookname.text=bookDetail.bookName
        databinding.bookdetailTvRating.text=StringUtil.float2PlainString(bookDetail.averageRating) + "分"
        databinding.bookdetailRating.setScore(bookDetail.averageRating.toInt())
        databinding.bookdetailTvAuthor.text=bookDetail.author
        databinding.bookdetailTvStatus.text=BookStatusHandler.handle(bookDetail.status)
        databinding.bookdetailTvTextCount.text="${StringUtil.float2PlainString (bookDetail.words/10000f)}万字"

        databinding.bookdetailTvDesc.text=bookDetail.description

        /*if(bookDetail.averageRating>0f){
            databinding.bookdetailRating.visibility=View.VISIBLE
        }else{
            databinding.bookdetailRating.visibility=View.GONE
        }*/
        GlideUtil.loadNetImage(databinding.bookdetailIvThumb,bookDetail.cover)

        showBookReadTip()

        //initRcv()
    }

    private fun showBookReadTip(){
        viewModel.getHadShowBookReadTip()
        if(!viewModel.hadShowBookReadTip){
            viewModel.setHadShowBookReadTip()
            val dialog=BookReadTipDialog(this)
            dialog.show()
            Observable.just("") .delay(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe{
                    dialog.dismiss()
                }
        }
    }

    /*private fun initComment(data: BookCommentListBean.DataBean){
        if(data.total>0){
            databinding.bookdetailTvCommentCount.text="书评·${data.total}"
        }else{
            databinding.bookdetailTvCommentCount.text="暂无评论"
        }

       databinding.bookdetailRcvComment.apply {
           layoutManager=LinearLayoutManager(context)
           mAdapter=BookCommentAdapter(data.records)
           adapter=mAdapter
       }
    }*/

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.bookdetail_ll_to_catalog->{
                val intent=Intent(this,BookCatalogActivity::class.java)
                //intent.putExtra("book_id",viewModel.bookId)
                intent.putExtra("book_detail",viewModel.bookDetail.value)
                startActivity(intent)
            }
            R.id.bookdetail_tv_more_comment->{
                if(viewModel.bookDetail.value==null) return
                val intent= Intent(v.context,MoreBookCommentActivity::class.java)
                intent.putExtra("book_detail",viewModel.bookDetail.value!!)
                v.context.startActivity(intent)
                //JumpUtil.toActivity(v.context,MoreBookCommentActivity::class.java)
            }
            R.id.bookdetail_btn_star->{
                addRemoveToShelf()
            }
            R.id.bookdetail_btn_read->{
                toBookReader()
            }
            R.id.bookdetail_ll->{
                toBookReader()
            }
            R.id.bookdetail_placeholder->{
                toBookReader()
            }
            R.id.bookdetail_ll_bottom_addto_shelf->{
                addRemoveToShelf()
            }
            R.id.bookdetail_btn_bottom_start_read->{
                toBookReader()
            }

        }
    }

    private fun addRemoveToShelf(){
        if(viewModel.isInBookShelf.value!!){
            viewModel.removeBookFromShelf()
            ToastUtil.show("已移出书架")
        }else{
            viewModel.addBookToShelf()
            ToastUtil.show("已添加到书架")
        }
    }

    private fun toBookReader(){
        //prevent jump reader page multi times
        if(viewModel.isToBookReader) return
        viewModel.isToBookReader=true
        val bookDetail=viewModel.bookDetail.value?:return
        val book=BookBean()
        book.id=bookDetail.bookId.toString()
        book.bookName=bookDetail.bookName
        book.thumb=bookDetail.cover
        book.isFromSDCard=false
        book.textCount=bookDetail.words
        book.author=bookDetail.author
        BusinessJumpUtil.toBookReader(book)
    }

    override fun onGestureFlipPage(direction: BookDetailGestureFrameLayout.FlipPageDirection) {
        if(BuildConfig.DEBUG) return
        if(direction == BookDetailGestureFrameLayout.FlipPageDirection.BOTTOM_TOP){
            if(databinding.bookdetailNsv.scrollY == databinding.bookdetailLl.measuredHeight - databinding.bookdetailNsv.measuredHeight){
                toBookReader()
            }
        }else{
            toBookReader()
        }
    }

}